#!/bin/sh
# ./ry.sh start 启动 stop 停止 restart 重启 status 状态
ACTIVE=$2
SERVERNAME=$3
JarName=mes-$SERVERNAME.jar
AppName=$JarName-$ACTIVE

# JVM参数
JVM_OPTS="-server -Dname=$AppName  -Duser.timezone=Asia/Shanghai -Xms512m -Xmx1024m"
APP_HOME=`pwd`

if [ "$1" = "" ];
then
    echo -e "\033[0;31m 未输入操作名 \033[0m  \033[0;34m {start|stop|restart|status|rebuild} \033[0m"
    exit 1
fi
if [ "$2" = "" ];
then
    echo -e "\033[0;31m 请输入active \033[0m  \033[0;34m {119|81} \033[0m"
    exit 1
fi
if [ SERVERNAME = "" ];
then
    SERVERNAME="admin"
fi

if [ "$AppName" = "" ];
then
    echo -e "\033[0;31m 未输入应用名 \033[0m"
    exit 1
fi

function status()
{
    PID=`ps -ef |grep java|grep $AppName|grep -v grep|wc -l`
    if [ $PID != 0 ];then
        echo "$AppName is running..."
    else
        echo "$AppName is not running..."
    fi
}


function start()
{
    PID=`ps -ef |grep java|grep $AppName|grep -v grep|awk '{print $2}'`

	if [ x"$PID" != x"" ]; then
	    echo "$AppName is running..."
	else
	  echo "nohup java $JVM_OPTS -jar mes/$SERVERNAME/$AppName  --spring.profiles.active=$ACTIVE > /dev/null 2>&1 &"
		nohup java $JVM_OPTS -jar mes/$SERVERNAME/$AppName  --spring.profiles.active=$ACTIVE  > /dev/null 2>&1 &
		echo "Start $AppName success..."
	fi
}

function stop()
{
    echo "Stop $AppName"

	PID=""
	query(){
		PID=`ps -ef |grep java|grep $AppName|grep -v grep|awk '{print $2}'`
	}

	query
	if [ x"$PID" != x"" ]; then
		kill -TERM $PID
		echo "$AppName (pid:$PID) exiting..."
		while [ x"$PID" != x"" ]
		do
			sleep 1
			query
		done
		echo "$AppName exited."
	else
		echo "$AppName already stopped."
	fi
}


function gitpull() {
  echo "==================git fetch======================"
  git fetch

  echo "==================git pull======================"
  git pull
}

function cleanPackage() {
  gitpull
  echo "==================mvn clean  package -Dmaven.test.skip=true======================"
  mvn clean  package -Dmaven.test.skip=true
}

function package()
{
  gitpull
  echo "===========mvn package -Dmaven.test.skip=true===================="
  mvn package -Dmaven.test.skip=true
}

function mkdirCommon() {
    if [ ! -d "mes/" ];then
    mkdir mes
  fi
  if [ ! -d "mes/$SERVERNAME" ];then
    mkdir mes/$SERVERNAME
  fi
}

function cpJar() {
 mkdirCommon
   \cp mes-$SERVERNAME/target/$JarName mes/$SERVERNAME/$AppName
}

function restart()
{
    cpJar
    stop
    sleep 2
    start
}


function rebuild()
{
    package
    sleep 2
    restart
}

function cleanbuild()
{
    cleanPackage
    sleep 2
    restart
}

case $1 in
  start)
    start;;
  stop)
    stop;;
  restart)
    restart;;
  status)
    status;;
  rebuild)
    rebuild;;
  cleanbuild)
    cleanbuild;;
  gitpull)
    gitpull;;
  *)


esac
